<template>
  <div class="mobile-container">
    <!-- 顶部标题栏 -->
    <header class="header">
      <img src="../../../assets/images/logo.png" alt="logo" class="logo">
      <div class="title-container">
        <div class="title">西大数信数帮学堂</div>
        <div class="sub-title">广西大学数学与信息科学学院</div>
      </div>
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="输入关键词搜索"
            class="search-input"
            size="small"
            clearable
            @keydown="handleSearchKeydown"
            @keyup.enter="performSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </header>

    <!-- 课程分类导航 -->
<!--    <div class="course-nav">
      <el-icon class="nav-arrow" @click="scrollNav('left')"><ArrowLeft /></el-icon>
      <div class="nav-items" ref="navScrollRef">
        <div
            v-for="(item, index) in channels"
            :key="index"
            class="nav-item"
            :class="{ 'active': currentNavIndex === index }"
            @click="changeNav(item)"
        >
          <div class="nav-icon" >
            <img :src="getImageUrl(item.iconName)" class="carousel-img"  @click="openSlideUrl('/mobile/channel/'+item.id)">
          </div>
          <span class="nav-label">{{ item.channelName }}</span>
        </div>
      </div>
      <el-icon class="nav-arrow" @click="scrollNav('right')"><ArrowRight /></el-icon>
    </div>-->

    <!-- 合集列表 -->
    <section class="content-section">
      <div class="section-header">
        <router-link to="/" title="返回首页">
          <i class="iconfont icon-back text-xl px-2 mr-2"></i>
        </router-link>
        <div v-for="(channel, index) in channels" :key="index">
          <h2 class="section-title" v-if="channel.id == channelId"> {{channel.channelName}}</h2>
        </div>


      </div>
      <div class="collection-list">
        <div
          v-for="(item, index) in newLists?.records || []"
          :key="index"
          class="collection-card"
          @click="goToVideo(item)"
        >
            <div class="collection-cover">
              <img :src="getImageUrl(item.bannerId)" :alt="item.title" loading="lazy">
              <div class="video-duration">{{ displayDuration(item?.duration ?? 0*1000) }}</div>
            </div>
            <div class="collection-info">
              <p class="collection-title">{{ item.title }}</p>
              <div class="collection-meta">
                <span class="up-tag">UP</span>
                <span class="author">{{ item.user.nickname }}</span>
              </div>
              <div class="collection-stats">
                <span><el-icon><VideoPlay /></el-icon>{{ item.plays }}</span>
              </div>
            </div>
        </div>
         <div v-if="loadingMore" class="loading-more">
          <div class="loading-spinner"></div>
          <span>加载中...</span>
        </div>
        
        <!-- 没有更多数据提示 -->
        <div v-else-if="!hasMore && newLists?.records?.length" class="no-more-data">
          没有更多数据了
        </div>

        <!-- 列表为空时显示提示 -->
        <div v-if="(!newLists?.records || newLists.records.length === 0) && !loading" class="empty-placeholder">
          <p class="empty-text">暂无视频</p>
        </div>
      </div>

    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, ArrowLeft, ArrowRight, VideoPlay } from '@element-plus/icons-vue'
import { listCarousels } from '@/apis/system';
import { imageUrl } from '@/apis/image';
import { listVideoChannels } from '@/apis/video/channel';
import videoApi from '@/apis/video';
import {displayDuration} from "@/utils/common.ts";
import { useAsyncState } from '@vueuse/core';

const { state } = useAsyncState(listCarousels({ position: 'HOME'}), null)
const { state: channels } = useAsyncState(listVideoChannels({
  child: true
}), [])

const router = useRouter()
const route = useRoute()

// 搜索关键词
const searchKeyword = ref('')
const tipIndex = ref(-1)
const tipList = ref([])
const currentSlideIndex = ref(0)
const currentNavIndex = ref(0)
const navScrollRef = ref<HTMLElement | null>(null)

// 添加键盘事件处理
function handleSearchKeydown(e: KeyboardEvent) {
  let offset = 0
  if (e.code === 'ArrowUp') {
    offset = -1
  } else if (e.code === 'ArrowDown') {
    offset = 1
  }

  if (offset) {
    e.preventDefault()
    const newIndex = tipIndex.value + offset
    if (newIndex >= tipList.value.length) {
      tipIndex.value = -1
    } else if(newIndex < -1) {
      tipIndex.value = tipList.value.length - 1
    } else {
      tipIndex.value = newIndex
    }
  }
}

const channelId = useRouteParams<number>('channelId')






// 执行搜索功能
function performSearch() {
  console.log('测试的辞keyword:', searchKeyword.value)
  // 检查是否已经在mobileSearch页面并且参数相同
  if (route.name === 'mobileSearch' && route.query.kw === searchKeyword.value) {
    console.log('Already on the same search page with same query')
    return
  }

  // 在这里添加实际的搜索逻辑
  router.push(`/mobileSearch?kw=${encodeURIComponent(searchKeyword.value)}`)
}



// 添加时间记录
const courseTimes = ref<Record<string, number>>({})

//点击视频
const  goToVideo = (value: Object) => {
  const url = generateVideoUrl(value)
  // 使用 Vue Router 在当前页面跳转
  router.push(url)
}

// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/mobile/play/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0

  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}


// 获取图片URL
function getImageUrl(bannerId: string) {
  return imageUrl + bannerId
}



//最新发布
const newparams = ref({
  pageNum: 1,
  pageSize: 8,
  type: 'VIDEO',
  keyword: '',
  sort: 'TIME',
  channelId: channelId.value
})
const currentPage = ref(1)
const hasMore = ref(true)
const loadingMore = ref(false)
// const { state: newLists } = useAsyncState(
//   videoApi.search(newparams.value),
//   { records: [] }
// )
const { state: newLists, isLoading, execute } = useAsyncState(
  videoApi.search(newparams.value),
  { records: [], current: 0, pages: 0, total: 0 }
)

// 下拉加载函数
const loadMore = async () => {
  // 如果正在加载或没有更多数据，直接返回
  if (loadingMore.value || !hasMore.value) return
  
  loadingMore.value = true
  try {
    // 增加页码
    const nextPage = currentPage.value + 1
    const params = {
      ...newparams.value,
      pageNum: nextPage
    }
    
    const result = await videoApi.search(params)
    
    if (result.records && result.records.length > 0) {
      // 追加新数据到现有列表
      newLists.value.records = [...newLists.value.records, ...result.records]
      currentPage.value = nextPage
      
      // 检查是否还有更多数据
      hasMore.value = nextPage < result.pages
    } else {
      hasMore.value = false
    }
  } catch (error) {
    console.error('加载更多数据失败:', error)
  } finally {
    loadingMore.value = false
  }
}

// 滚动处理函数
const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 当滚动到底部附近时触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadMore()
  }
}

// 添加滚动事件监听
onMounted(() => {
  const contentSection = document.querySelector('.collection-list')
  if (contentSection) {
    contentSection.addEventListener('scroll', handleScroll)
  }
})

// 移除滚动事件监听
onUnmounted(() => {
  const contentSection = document.querySelector('.collection-list')
  if (contentSection) {
    contentSection.removeEventListener('scroll', handleScroll)
  }
})



</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
  height: auto;
  display: block;
}

:global(html) {
  overflow-x: hidden;
  width: 100%;
}

:global(body) {
  overflow-x: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

.mobile-container {
  --header-height: 50px;
  --spacing-xs: 8px;
  --spacing-sm: 12px;
  --spacing-md: 16px;
  --spacing-lg: 24px;
  --border-radius: 8px;

  height:  calc(100vh - 90px);
  background-color: #f5f5f5;
  -webkit-tap-highlight-color: transparent;
  font-family: "Microsoft Yahei", "Heiti SC", sans-serif;
  overflow-x: hidden;
  width: 100%;
  max-width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;

  & > * {
    max-width: 100%;
  }
}

// 头部样式
.header {
  display: flex;
  align-items: center;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)),
  url('@/assets/images/home_banner/1sz3p8w2Sk.png@3840w_400h_1c.webp');
  background-size: cover;
  background-position: center;
  backdrop-filter: blur(2px);
  padding: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 999;
  gap: 10px;
  width: 100%;
  box-sizing: border-box;
  height: var(--header-height);

  .logo {
    width: 36px;
    height: 36px;
    min-width: 36px;
    border-radius: 6px;
    flex-shrink: 0;
    object-fit: cover;
  }

  .title-container {
    flex: 1;
    min-width: 0;

    .title {
      font-size: 14px;
      font-weight: 600;
      line-height: 1.2;
      color: #222;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 2px;
    }

    .sub-title {
      font-size: 10px;
      color: #888;
      line-height: 1.2;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .search-box {
    flex: 0 0 40%;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .search-input {
      width: 100%;

      :deep(.el-input__wrapper) {
        border-radius: 18px;
        background-color: #ffffff;
        box-shadow: none;
        padding: 4px 12px;
        min-height: 32px;
      }

      :deep(.el-input__inner) {
        font-size: 12px;
        color: #666;

        &::placeholder {
          color: #999;
        }
      }

      :deep(.el-input__prefix) {
        color: #999;
        font-size: 12px;
        margin-right: 6px;
      }
    }
  }
}

// 课程导航
.course-nav {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 8px;
  gap: 8px;
  margin-top: 0;
  width: 100%;
  box-sizing: border-box;

  .nav-arrow {
    flex-shrink: 0;
    font-size: 18px;
    color: #bbb;
    cursor: pointer;
    padding: 4px;
    transition: color 0.3s ease;

    &:hover {
      color: #666;
    }
  }

  .nav-items {
    flex: 1;
    display: flex;
    overflow-x: auto;
    scroll-behavior: smooth;
    gap: 10px;
    padding: 5px 0;
    min-width: 0;

    &::-webkit-scrollbar {
      display: none;
    }

    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      min-width: 52px;
      max-width: 52px;
      cursor: pointer;
      flex-shrink: 0;
      transition: all 0.3s ease;
      // 设置固定高度以便计算比例
      height: 60px;

      .nav-icon {
        // 占据2/3高度 (60px * 2/3 = 40px)
        width: 100%;
        height: 40px;
        // 圆角图标样式
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4px;
        transition: transform 0.3s ease;
        overflow: hidden;

        .icon-emoji {
          font-size: 22px;
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          // 保持圆角效果
          border-radius: 8px;
        }
      }

      .nav-label {
        font-size: 11px;
        color: #333;
        white-space: nowrap;
        transition: all 0.3s ease;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 100%;
        // 占据1/3高度 (60px * 1/3 = 20px)
        height: 20px;
        line-height: 20px;
      }

      &:hover {
        .nav-icon {
          transform: scale(1.05);
        }
      }

      &.active {
        .nav-label {
          color: #FF6B35;
          font-weight: 500;
          position: relative;

          &::after {
            content: '';
            position: absolute;
            bottom: -3px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 2.5px;
            background-color: #FF6B35;
            border-radius: 1.5px;
          }
        }
      }
    }
  }
}

// 内容区域
// 修改内容区域样式部分
.content-section {
  flex-grow: 1; /* 让内容区域填充剩余空间 */
  .section-header {
    display: flex;
    justify-content: space-between; // 使用 space-between 布局
    align-items: center;
    margin-bottom: var(--spacing-sm);
    width: 100%;
    position: relative;
    height: 6%;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      position: absolute;
      left: 50%;
      transform: translateX(-50%); // 绝对定位居中
    }

    .more-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 10px;
      font-size: 14px;
      color: #999;
      background: none;
      border: none;
      cursor: pointer;
      transition: color 0.3s ease;
      border-radius: 4px;

      &:hover {
        color: #409eff;
        background-color: #f5f5f5;
      }

      .header-placeholder {
        width: 32px; // 与返回按钮宽度相当，保持平衡
      }
    }
  }
}


// 合集列表
.collection-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  width: 100%;
  height: 93%;

  .collection-card {
    display: flex;
    background-color: #fff;
    border-radius: var(--border-radius);
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s ease;
    width: 100%;
    max-width: 100%;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    &:active {
      transform: scale(0.98);
    }

    .collection-cover {
      position: relative;
      width: 120px;
      flex-shrink: 0;
      background-color: #f0f0f0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-duration {
        position: absolute;
        bottom: 4px;
        right: 4px;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 5px;
        border-radius: 2px;
        font-size: 10px;
      }
    }

    .collection-info {
      flex: 1;
      padding: var(--spacing-sm);
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .collection-title {
        font-size: 14px;
        line-height: 1.4;
        color: #333;
        margin-bottom: 6px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .collection-meta {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        margin-bottom: 6px;

        .up-tag {
          background-color: #e8f4ff;
          color: #409eff;
          padding: 1px 5px;
          border-radius: 2px;
          font-weight: 500;
        }

        .author {
          color: #666;
        }
      }

      .collection-stats {
        display: flex;
        gap: 10px;
        font-size: 12px;
        color: #999;

        span {
          display: flex;
          align-items: center;
          gap: 3px;
        }
      }
    }
  }
  .loading-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 15px;
    gap: 10px;
    color: #666;
    
    .loading-spinner {
      width: 20px;
      height: 20px;
      border: 2px solid #f3f3f3;
      border-top: 2px solid #409eff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  }
  
  .no-more-data {
    text-align: center;
    padding: 15px;
    color: #999;
    font-size: 14px;
  }
  
  .empty-placeholder {
    text-align: center;
    padding: 40px 20px;
    
    .empty-text {
      font-size: 14px;
      color: #999;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .mobile-container {
    --header-height: 48px;
    --spacing-xs: 6px;
    --spacing-sm: 10px;
    --spacing-md: 14px;
    --spacing-lg: 20px;
  }

  .header {
    padding: 8px;
    gap: 8px;

    .logo {
      width: 32px;
      height: 32px;
    }

    .title {
      font-size: 13px;
    }

    .sub-title {
      font-size: 9px;
    }

    .search-box {
      .search-input {
        :deep(.el-input__wrapper) {
          padding: 3px 10px;
          min-height: 28px;
        }

        :deep(.el-input__inner) {
          font-size: 11px;
        }
      }
    }
  }

  .content-section {
    padding: var(--spacing-sm) var(--spacing-sm);

    .section-header {
      .section-title {
        font-size: 16px;
      }

      .more-btn {
        padding: 5px 8px;
        font-size: 13px;
      }
    }
  }

  .collection-list {
    .collection-card {
      .collection-cover {
        width: 100px;
      }

      .collection-info {
        padding: var(--spacing-xs);

        .collection-title {
          font-size: 13px;
        }

        .collection-meta {
          font-size: 11px;
        }

        .collection-stats {
          font-size: 11px;
          gap: 8px;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .mobile-container {
    --header-height: 44px;
    --spacing-xs: 5px;
    --spacing-sm: 8px;
    --spacing-md: 12px;
    --spacing-lg: 16px;
  }

  .header {
    padding: 6px;
    gap: 6px;

    .logo {
      width: 28px;
      height: 28px;
    }

    .title-container {
      .title {
        font-size: 12px;
      }

      .sub-title {
        font-size: 8px;
      }
    }

    .search-box {
      flex: 0 0 35%;

      .search-input {
        :deep(.el-input__wrapper) {
          padding: 2px 8px;
          min-height: 26px;
          border-radius: 15px;
        }

        :deep(.el-input__inner) {
          font-size: 10px;
        }

        :deep(.el-input__prefix) {
          font-size: 10px;
        }
      }
    }
  }

  .collection-list {
    .collection-card {
      .collection-cover {
        width: 90px;
      }

      .collection-info {
        .collection-title {
          font-size: 12px;
        }

        .collection-meta {
          font-size: 10px;
        }

        .collection-stats {
          font-size: 10px;
          gap: 8px;
        }
      }
    }
  }
}
.collection-list {
  // ... existing styles ...

  .empty-placeholder {
    text-align: center;
    padding: 40px 20px;

    .empty-text {
      font-size: 14px;
      color: #999;
    }
  }
}



</style>
